<script setup lang="ts">
import ArchiveSelector from '@/components/common/ArchiveSelector.vue'
import {ref, reactive, computed, watch, onMounted} from 'vue'
import {getProjectDocumentListApi} from '@/api/project'
import {ProjectDocument, ProjectDocumentListParam} from '@/api/project/type'
import {getListApi} from '@/api/software'
import {
  SoftwareWarehouse,
  SoftwareWarehouseListParam,
} from '@/api/software/type'
import {
  getDetailApi,
  submitUpdateSoftwarePlan,
  submitSoftwarePricingPlanApi,
  getSoftwarePlanApi,
} from '@/api/softwarePricingPlan/index'
import {MaterialItem, softwarePlan} from '@/api/softwarePricingPlan/type'
import {getListApi as getDictDataApi} from '@/api/sysDictData'
import {SysDictDataListParam} from '@/api/sysDictData/type'
import {ElMessage} from 'element-plus'
import {Check, Close, Delete, Plus, QuestionFilled} from '@element-plus/icons-vue'
// 引入vue-router
import {useRoute} from 'vue-router'
// 获取路由实例
const route = useRoute()
// 引入vue-router
import {useRouter} from 'vue-router'
import MaterialDialog from '@/views/baseInfo/material/materialDialog/index.vue'

// 获取路由实例
const router = useRouter()

// 判断是否为查看模式
const isViewMode = computed(() => route.query.mode === 'view')

interface Material {
  id: number
  materialName: string
  purchasePrice: number

  [key: string]: any
}

// 项目状态映射
const statusOptions = [
  {value: 0, label: '进行中'},
  {value: 1, label: '已完成'},
  {value: 2, label: '已暂停'},
  {value: 3, label: '已取消'},
]

// 仓库选择器相关数据
const warehouseSelectorVisible = ref(false)
const selectedWarehouse = ref<SoftwareWarehouse | null>(null)

// 项目选择器相关数据
const projectSelectorVisible = ref(false)
const selectedProject = ref<ProjectDocument | null>(null)

// 仓库选择器搜索字段配置
const warehouseSearchFields = [
  {label: '仓库名称', prop: 'name', type: 'input' as const},
]

// 仓库选择器表格列配置
const warehouseTableColumns = [
  {prop: 'name', label: '仓库名称', width: 280},
  {prop: 'remark', label: '备注'},
]

// 项目选择器搜索字段配置
const projectSearchFields = [
  {label: '项目名称', prop: 'name', type: 'input' as const},
  {label: '项目编号', prop: 'code', type: 'input' as const},
  {label: '客户名称', prop: 'customer', type: 'input' as const},
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions,
  },
]

// 项目选择器表格列配置
const projectTableColumns = [
  {prop: 'name', label: '项目名称', width: 250},
  {prop: 'code', label: '项目编号', width: 250},
  {prop: 'customer', label: '客户名称', width: 250},
  {prop: 'manager', label: '项目经理', width: 200},
]

// 获取仓库列表数据的API方法
const getWarehouseList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: SoftwareWarehouseListParam = {
      name: params.name,
      page: params.page || 1,
      limit: params.limit || 10,
    }

    // 调用仓库列表API - 使用真实API
    return await getListApi(queryParams)
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    return {data: {list: [], total: 0}}
  }
}

// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10,
    }

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return {data: {list: [], total: 0}}
  }
}

// 处理仓库选择确认
const handleWarehouseSelect = (warehouse: SoftwareWarehouse) => {
  selectedWarehouse.value = warehouse
  console.log('选择的仓库:', warehouse)
  form.repositoryId = Number(warehouse.id) || undefined

  // 如果已有项目金额，可以自动获取相关金额数据
  if (form.projectAmount > 0) {
    fetchPricingDetail()
  }
}

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project
  console.log('选择的项目:', project)
  form.projectId = Number(project.id) || undefined
}

// 打开仓库选择器
const openWarehouseSelector = () => {
  warehouseSelectorVisible.value = true
}

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true
}

// 获取价格明细数据
const fetchPricingDetail = async () => {
  if (!form.repositoryId || form.projectAmount <= 0) {
    return
  }
  try {
    // 使用表单中的仓库数量
    const quantity = form.warehouseQuantity

    const response = await getDetailApi(
        form.repositoryId,
        quantity,
        form.projectAmount
    )

    if (response && response.data) {
      // 回填数据
      form.wmsAmount = response.data.wms || 0
      form.wcsAmount = response.data.wcs || 0
      form.interfaceAmount = response.data.ap || 0
      form.baseImplementationFee = response.data.implementationFee || 0

      // 重新计算总价
      calculateTotals()

      ElMessage.success('已自动获取价格明细')
    }
  } catch (error) {
    console.error('获取价格明细失败:', error)
    ElMessage.error('获取价格明细失败，请手动填写')
  }
}

// 选择基础物料相关
const baseMaterialDialogRef = ref()
// 多选模式选中的物料列表
const selectedMaterials = ref<any[]>([])
// 单选模式选中的物料（为了兼容旧代码）
const selectedMaterial = ref<any>(null)

// 打开物料选择弹框
const openBaseMaterialSelect = () => {
  console.log('多选模式选中的物料列表' + selectedMaterials.value)
  baseMaterialDialogRef.value.onShow(selectedMaterials.value)
}

// 多选模式下物料选择变化时的处理函数
const handleMaterialSelectionChange = (selection: any) => {
  console.log('已选物料:' + selection)

  // 获取当前选中的物料ID集合，确保ID为数字类型
  const selectedIds = selection.map((item: any) => Number(item.id))
  // 从 form.materialItems 中移除已取消勾选的物料
  form.materialItems = form.materialItems.filter((item) => {
    // 保留仍在选中状态的物料，确保类型匹配
    return selectedIds.includes(Number(item.materialId))
  })

  // 2. 更新 目前已选中的物料
  selectedMaterials.value = selection

  // 3. 为每个选中的物料初始化数量和计算总价
  /*  selectedMaterials.value.forEach((material) => {
    initMaterialQuantity(material)
  })*/

  // 4. 更新表格数据（添加新选中的物料）
  updateTableList()
}
// 确认物料多选完成时的处理函数
const confirmMaterialSelect = () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }
  ElMessage.success(`已选择 ${selectedMaterials.value.length} 个物料`)
  baseMaterialDialogRef.value.onClose()
  // 这里可以进行后续处理，例如将选中的物料添加到表单中
  console.log('选中的物料列表:', selectedMaterials.value)
}

// 更新表格数据列表
const updateTableList = () => {
  // 将选择的物料添加到表格数据中，避免重复
  selectedMaterials.value.forEach((material) => {
    console.log('选中的物料列表:', material)
    if (!form.materialItems.some((item) => Number(item.materialId) === Number(material.id))) {
      form.materialItems.push({
        materialId: Number(material.id), // 确保转换为数字类型
        materialName: material.materialName,
        brand: material.brand,
        purchasePrice: Number(material.price || 0), // 确保转换为数字类型
        quantity: Number(material.quantity || 1), // 确保转换为数字类型
        totalPrice: Number((material.price || 0) * (material.quantity || 1)), // 确保转换为数字类型
      })
    }
  })
  // 更新物料基础价格和最终价格
  updateMaterialBasePrice()
  
  // 更新所有自动计算的数量
  updateAllAutoCalculatedQuantities()
}

// 更新物料基础价格（所有物料的总价）
const updateMaterialBasePrice = () => {
  // 计算所有物料的总价，确保数值类型正确
  form.materialBasePrice = form.materialItems.reduce((total, item) => {
    const itemTotal = Number(item.totalPrice) || 0
    return total + itemTotal
  }, 0)

  // 应用系数计算最终价格
  updateMaterialPrice()
}

// 删除选中的物料
const removeMaterialItem = (index: number) => {
  // 从表格数据中删除
  const removedItem = form.materialItems.splice(index, 1)[0]
  console.log('删除的元素：' + removedItem.materialName)
  // 从已选物料中也删除，确保ID类型匹配
  selectedMaterials.value = selectedMaterials.value.filter(
      (item) => Number(item.id) !== Number(removedItem.materialId)
  )
  console.log('剩余元素个数：' + selectedMaterials.value.length)
  // 更新物料基础价格和最终价格
  updateMaterialBasePrice()
  
  // 更新所有自动计算的数量
  updateAllAutoCalculatedQuantities()
}

// 修改物料数量
const handleMaterialQuantityChange = (row: any) => {
  // 确保数值类型正确，更新总价
  row.quantity = Number(row.quantity) || 1
  row.purchasePrice = Number(row.purchasePrice) || 0
  row.totalPrice = Number(row.quantity * row.purchasePrice)

  // 更新物料基础价格和最终价格
  updateMaterialBasePrice()
  
  // 更新所有自动计算的数量
  updateAllAutoCalculatedQuantities()
}

// 软件核价表单数据
const form = reactive(<softwarePlan>{
  id: undefined, // ID
  projectId: undefined, // 项目ID
  repositoryId: undefined, // 仓库ID
  projectAmount: 0, // 项目金额
  warehouseQuantity: 1, // 仓库数量
  wmsAmount: 0, // WMS费用
  wcsAmount: 0, // WCS费用
  interfaceAmount: 0, // 接口费用
  baseImplementationFee: 0, // 基础实施费
  materialId: undefined, // 物料ID
  materialPrice: 0, // 物料价格
  materialBasePrice: 0, // 物料基础价格（未加成前）
  materialCoefficient: 1, // 物料系数加成
  totalImplementationPrice: 0, // 实施费总价
  implementationCoefficient: 1, // 实施费系数加成
  totalPrice: 0, // 总价
  extraCost: 0, // 额外费用
  extraCostDescription: '', // 额外费用说明
  remark: '', // 备注
  implementationItem: [], // 实施项表格数据
  materialItems: [], // 物料列表
})

// 实施项名称选项
const implementationNameOptions = ref([
  {label: '基础实施费', value: '基础实施费', price: 200},
  {label: 'WMS用AP数量', value: 'WMS用AP数量', price: 600},
  {label: '电视机数量', value: '电视机数量', price: 400},
  {label: '一体机数量', value: '一体机数量', price: 300},
])

// 实施总价系数加成
const coefficientOptions = ref([{label: '国外项目', value: '1.15'}])

// 物料系数加成
const materialsOptions = ref([{label: '采购价系数', value: '1.17'}])

// 实施项名称改变时带出单价
const handleImplementationNameChange = (row: any) => {
  // 如果是基础实施费项，使用form中的基数值
  if (row.name === '基础实施费') {
    row.isBaseImplementation = true
    row.unitPrice = form.baseImplementationFee
  } else {
    // 不是基础实施费项，使用字典选项中的单价
    row.isBaseImplementation = false
    const option = implementationNameOptions.value.find(
        (item) => item.value === row.name
    )
    if (option) {
      row.unitPrice = option.price
    }
  }

  // 更新总价
  row.totalPrice = row.quantity * row.unitPrice
  calculateTotals()
}

// 实施项数量改变时计算总价
const handleQuantityChange = (row: any) => {
  row.totalPrice = row.quantity * row.unitPrice
  calculateTotals()

  // 如果修改的是基础实施费行，更新基数
  if (row.isBaseImplementation) {
    form.baseImplementationFee = row.unitPrice
  }
}

// 添加实施项
const addImplementationItem = () => {
  form.implementationItem.push({
    name: '',
    quantity: 1,
    unitPrice: 0,
    totalPrice: 0,
    isBaseImplementation: false,
  })
}

// 删除实施项
const removeImplementationItem = (index: number) => {
  form.implementationItem.splice(index, 1)
  calculateTotals()
}

// 处理系数选择
const handleCoefficientChange = (value: number) => {
  form.implementationCoefficient = value
  calculateTotals()
}
// 计算实施总价
const calculateTotals = () => {
  // 实施项小计 = 所有实施项总价之和
  const implementationSubtotal = form.implementationItem.reduce(
      (total, item) => total + item.totalPrice,
      0
  )

  // 实施总价 = 实施项小计 * 系数
  form.totalImplementationPrice =
      implementationSubtotal * form.implementationCoefficient

  // 计算最终总价
  form.totalPrice =
      form.wmsAmount +
      form.wcsAmount +
      form.interfaceAmount +
      form.totalImplementationPrice +
      form.materialPrice +
      form.extraCost
}

// 监听所有可能影响总价的字段变化
watch(
    () => [
      form.projectAmount,
      form.wmsAmount,
      form.wcsAmount,
      form.interfaceAmount,
      form.baseImplementationFee,
      form.materialPrice,
      form.extraCost,
    ],
    () => {
      calculateTotals()
    },
    {deep: true}
)

// 监听实施费基数变化，更新基础实施费行的价格
watch(
    () => form.baseImplementationFee,
    (newValue) => {
      // 找到基础实施费行
      const baseImplementationItem = form.implementationItem.find(
          (item) => item.isBaseImplementation
      )
      if (baseImplementationItem) {
        baseImplementationItem.unitPrice = newValue
        baseImplementationItem.totalPrice =
            baseImplementationItem.quantity * newValue
        calculateTotals()
      }
    },
    {immediate: true} // 立即触发一次，确保初始化时设置正确的值
)

// 监听物料列表变化，自动更新所有相关数量
watch(
    () => form.materialItems,
    () => {
      // 当物料列表发生变化时，自动更新所有相关的实施项数量
      updateAllAutoCalculatedQuantities()
    },
    {deep: true} // 深度监听数组内对象的变化
)

// 实施项总价
const implementationItemsTotal = computed(() => {
  return form.implementationItem.reduce((sum, item) => sum + item.totalPrice, 0)
})

// 提交表单
const submitForm = async () => {
  // 验证必要字段
  if (!form.projectId || form.projectId <= 0) {
    ElMessage.warning('请选择项目')
    return
  }

  if (!form.repositoryId || form.repositoryId <= 0) {
    ElMessage.warning('请选择仓库')
    return
  }

  if (!form.projectAmount || form.projectAmount <= 0) {
    ElMessage.warning('项目金额必须大于0')
    return
  }

  // 构造提交数据，确保数据类型正确
  const submitData = {
    ...form,
    // 确保物料明细中的数据类型正确
    materialItems: form.materialItems.map(item => ({
      ...item,
      materialId: Number(item.materialId),
      quantity: Number(item.quantity),
      purchasePrice: Number(item.purchasePrice),
      totalPrice: Number(item.totalPrice),
    })),
    // 确保实施项中的数据类型正确
    implementationItem: form.implementationItem.map(item => ({
      ...item,
      quantity: Number(item.quantity),
      unitPrice: Number(item.unitPrice),
      totalPrice: Number(item.totalPrice),
    }))
  }
  console.log('提交数据:', submitData)
  try {
    console.log('准备提交的数据:', JSON.stringify(submitData, null, 2))
    
    // 判断是新增还是修改
    if (form.id) {
      // 修改
      await submitUpdateSoftwarePlan(submitData)
      ElMessage.success('修改成功')
      resetForm()
    } else {
      // 新增
      await submitSoftwarePricingPlanApi(submitData)
      ElMessage.success('提交成功')
      resetForm()
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    // 提取错误信息
    let errorMessage = '提交失败'
    if (error?.response?.data?.message) {
      errorMessage = error.response.data.message
      
      // 处理特定的数据库错误
      if (errorMessage.includes('Duplicate entry') && errorMessage.includes('PRIMARY')) {
        errorMessage = '数据保存冲突，请刷新页面后重试'
      }
    } else if (error?.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
    
    // 如果是主键冲突错误，建议用户刷新页面
    if (errorMessage.includes('数据保存冲突')) {
      setTimeout(() => {
        ElMessage({
          message: '建议刷新页面获取最新数据',
          type: 'warning',
          duration: 5000
        })
      }, 2000)
    }
  }
}

// 返回
const resetForm = () => {
  router.push(`/softwarePlan`)
}

// 处理项目金额变化
const onProjectAmountChange = (value: number) => {
  if (value > 0 && form.repositoryId) {
    fetchPricingDetail()
  }
}

// 处理仓库数量变化
const onWarehouseQuantityChange = (value: number) => {
  if (value > 0 && form.repositoryId && form.projectAmount > 0) {
    fetchPricingDetail()
  }
}

// 获取实施项配置项
const getImplementationItems = async () => {
  try {
    // 构建查询参数
    const queryParams: SysDictDataListParam = {
      dictType: 'Implement the_project',
      page: 1,
      limit: 10,
    }
    const response = await getDictDataApi(queryParams)
    const dataList = response.data.list
    implementationNameOptions.value = dataList.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictLabel,
      price: item.dictValue,
    }))
  } catch (error) {
    console.error('获取实施项失败:', error)
  }
}

// 获取实施总价系数加成配置项
const getCoefficientOptions = async () => {
  try {
    // 构建查询参数
    const queryParams: SysDictDataListParam = {
      dictType: 'Implementation_coefficient',
      page: 1,
      limit: 10,
    }
    // 调用项目列表API - 使用真实API
    const response = await getDictDataApi(queryParams)
    const dataList = response.data.list
    coefficientOptions.value = dataList.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictValue,
    }))
  } catch (error) {
    console.error('获取实施项失败:', error)
  }
}

// 获取物料系数加成(采购价加成系数)
const getMaterialsOptions = async () => {
  try {
    // 构建查询参数
    const queryParams: SysDictDataListParam = {
      dictType: 'software_purchase_price',
      page: 1,
      limit: 10,
    }
    // 调用项目列表API - 使用真实API
    const response = await getDictDataApi(queryParams)
    const dataList = response.data.list
    materialsOptions.value = dataList.map((item: any) => ({
      label: item.dictLabel,
      value: item.dictValue,
    }))
  } catch (error) {
    console.error('获取采购价加成系数失败:', error)
  }
}

// 处理物料系数选择
const handleMaterialCoefficientChange = (value: number) => {
  form.materialCoefficient = value
  // 重新计算物料价格
  updateMaterialPrice()
}

// 更新物料价格（应用系数）
const updateMaterialPrice = () => {
  form.materialPrice = form.materialBasePrice * form.materialCoefficient
  calculateTotals()
}

// 计算物料明细中包含特定关键词的总数量
const calculateMaterialQuantityByKeyword = (keyword: string) => {
  return form.materialItems.reduce((total, item) => {
    // 检查物料名称是否包含指定关键词（不区分大小写）
    if (item.materialName && item.materialName.toUpperCase().includes(keyword.toUpperCase())) {
      return total + (Number(item.quantity) || 0)
    }
    return total
  }, 0)
}

// 更新实施项明细中指定名称项的数量
const updateImplementationItemQuantity = (itemName: string, keyword: string) => {
  const quantity = calculateMaterialQuantityByKeyword(keyword)
  
  // 查找实施项中指定名称的项
  const implementationItem = form.implementationItem.find(
    (item) => item.name === itemName
  )
  
  if (implementationItem) {
    // 更新数量
    implementationItem.quantity = quantity
    // 重新计算总价
    implementationItem.totalPrice = implementationItem.quantity * implementationItem.unitPrice
    // 重新计算总计
    calculateTotals()
    
    console.log(`已更新${itemName}: ${quantity}`)
  }
}

// 计算物料明细中包含'AP'的总数量（保持向后兼容）
const calculateApQuantity = () => {
  return calculateMaterialQuantityByKeyword('AP')
}

// 更新实施项明细中'WMS用AP数量'的数量（保持向后兼容）
const updateApQuantityInImplementation = () => {
  updateImplementationItemQuantity('WMS用AP数量', 'AP')
}

// 更新所有自动计算的实施项数量
const updateAllAutoCalculatedQuantities = () => {
  // 更新WMS用AP数量
  updateImplementationItemQuantity('WMS用AP数量', 'AP')
  // 更新电视机数量（根据包含'显示屏'的物料）
  updateImplementationItemQuantity('电视机数量', '显示屏')
  // 更新一体机数量（根据包含'一体机'的物料）
  updateImplementationItemQuantity('一体机数量', '一体机')
}

// 页面加载状态
const pageLoading = ref(false)

// 获取详情数据
const getSoftwarePlan = async () => {
  // 显示页面加载状态
  pageLoading.value = true
  try {
    if (route.params.id) {
      console.log('获取到的参数：' + route.params.id)
      const res = await getSoftwarePlanApi(route.params.id as string)
      // 填充表单数据
      form.id = res.data.id
      form.projectId = res.data.projectId || 0
      form.repositoryId = res.data.repositoryId || 0
      form.projectAmount = res.data.projectAmount || 0
      form.warehouseQuantity = res.data.warehouseQuantity || 1
      form.wmsAmount = res.data.wmsAmount || 0
      form.wcsAmount = res.data.wcsAmount || 0
      form.interfaceAmount = res.data.interfaceAmount || 0
      form.baseImplementationFee = res.data.baseImplementationFee || 0
      form.materialId = res.data.materialId || 0
      form.materialBasePrice = res.data.materialBasePrice || 0
      form.materialPrice = res.data.materialPrice || 0
      form.materialCoefficient = res.data.materialCoefficient || 1
      form.implementationCoefficient = res.data.implementationCoefficient || 1
      form.totalImplementationPrice = res.data.totalImplementationPrice || 0
      form.extraCost = res.data.extraCost || 0
      form.extraCostDescription = res.data.extraCostDescription || ''
      form.remark = res.data.remark || ''
      form.totalPrice = res.data.totalPrice || 0

      // 如果有实施项数据，则填充
      if (
          res.data.implementationItem &&
          res.data.implementationItem.length > 0
      ) {
        form.implementationItem = res.data.implementationItem.map(
            (item: any) => ({
              name: item.name || '',
              quantity: item.quantity || 1,
              unitPrice: item.unitPrice || 0,
              totalPrice: item.totalPrice || 0,
              isBaseImplementation: item.name === '基础实施费',
            })
        )
      } else {
        // 如果没有实施项数据，则添加一个基础实施费行
        form.implementationItem = [
          {
            name: '基础实施费',
            quantity: 1,
            unitPrice: form.baseImplementationFee,
            totalPrice: form.baseImplementationFee,
            isBaseImplementation: true,
          },
        ]
      }

      // 填充选择器数据
      if (res.data.repositoryName) {
        selectedWarehouse.value = {
          id: form.repositoryId,
          name: res.data.repositoryName,
          remark: res.data.repositoryRemark || '',
        }
      }

      if (res.data.projectName) {
        selectedProject.value = {
          id: form.projectId,
          name: res.data.projectName,
          code: res.data.projectCode || '',
          customerName: res.data.projectCustomer || '',
          status: res.data.projectStatus,
        } as ProjectDocument
      }

      // 加载物料数据
      if (res.data.materialItems && res.data.materialItems.length > 0) {
        // 确保所有数值字段都是正确的类型
        form.materialItems = res.data.materialItems.map((item: any) => ({
          materialId: Number(item.materialId),
          materialName: item.materialName,
          brand: item.brand,
          purchasePrice: Number(item.purchasePrice || 0),
          quantity: Number(item.quantity || 1),
          totalPrice: Number(item.totalPrice || 0),
        }))
        
        // 转换为选中的物料列表
        selectedMaterials.value = res.data.materialItems.map((item: any) => ({
          id: Number(item.materialId),
          materialName: item.materialName,
          brand: item.brand,
          price: Number(item.purchasePrice || 0), // 注意这里使用price字段
          quantity: Number(item.quantity || 1),
        }))
      }

      // 兼容旧版单选模式的数据
      if (res.data.materialName) {
        selectedMaterial.value = {
          id: form.materialId as number,
          materialName: res.data.materialName,
          purchasePrice: form.materialBasePrice,
        }
      }
      // 重新计算总价
      calculateTotals()
      
      // 更新所有自动计算的数量（如果有物料数据）
      if (form.materialItems.length > 0) {
        updateAllAutoCalculatedQuantities()
      }
      
      ElMessage.success('加载数据成功')
    } else {
      // 新增的默认初始化掉4项实施
      implementationNameOptions.value.forEach((option) => {
        form.implementationItem.push({
          name: option.label,
          quantity: 1,
          unitPrice: option.price,
          totalPrice: option.price,
          isBaseImplementation: option.label === '基础实施费',
        })
      })
    }
  } catch (error) {
    console.error('软件报价单详情:', error)
    ElMessage.error('加载数据失败')
  } finally {
    // 隐藏页面加载状态
    pageLoading.value = false
  }
}


// 软件核价单注意事项提示
const softwarePlanNotice = ref('');
// 软件核价单实施项提示
const implementationItemNotice = ref<string>('');

const getSoftwarePlanNotice = async () => {
  try {
    // 构建查询参数
    const queryParams: SysDictDataListParam = {
      dictType: 'softwareTip',
      page: 1,
      limit: 10,
    }
    // 调用项目列表API - 使用真实API
    const response = await getDictDataApi(queryParams)
    const dataList = response.data.list
    softwarePlanNotice.value = dataList[0].dictValue || '';
    implementationItemNotice.value = dataList[1].dictValue || '';
  }catch (Error) {

  }
}


onMounted(() => {
  // 获取实施项列表
  getImplementationItems()
  // 获取实施总价系数加成配置项
  getCoefficientOptions()
  // 物料软件采购系数
  getMaterialsOptions()
  // 获取详情数据(用于编辑，新增时不用)
  getSoftwarePlan()
  // 获取软件核价单提示
  getSoftwarePlanNotice()
})
</script>

<template>
  <!-- 主容器 -->
  <div class="pricing-container"
       v-loading="pageLoading"
       element-loading-text="数据加载中..."
       element-loading-background="rgba(255, 255, 255, 0.7)">
    <div class="page-header">
      <h2>{{ isViewMode ? '查看软件核价单' : '软件核价单' }}</h2>
    </div>

    <!-- 软件核价表单 -->
    <el-form :model="form"
             label-position="top"
             :disabled="isViewMode"
             class="pricing-form">
      <!-- 基础信息卡片 -->
      <el-card class="form-card"
               shadow="hover">
        <template #header>
          <div class="card-header">
            <span>基础信息</span>
          </div>
        </template>

        <el-row :gutter="24">
          <!-- 项目选择 -->
          <el-col :xs="24"
                  :sm="12"
                  :md="8">
            <el-form-item label="项目信息"
                          required>
              <el-input :model-value="selectedProject ? selectedProject.name : ''"
                        placeholder="请选择项目"
                        readonly
                        :disabled="isViewMode"
                        class="selector-input">
                <template #append>
                  <el-button @click="openProjectSelector" :disabled="isViewMode">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <!-- 仓库选择 -->
          <el-col :xs="24"
                  :sm="12"
                  :md="8">
            <el-form-item label="仓库信息"
                          required>
              <el-input :model-value="selectedWarehouse ? selectedWarehouse.name : ''"
                        placeholder="请选择仓库"
                        readonly
                        :disabled="isViewMode"
                        class="selector-input">
                <template #append>
                  <el-button @click="openWarehouseSelector" :disabled="isViewMode">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 金额信息卡片 -->
      <el-card class="form-card"
               shadow="hover">
        <template #header>
          <div class="card-header">
            <span>金额信息</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :xs="24"
                  :sm="12"
                  :md="8"
                  :lg="6">
            <el-form-item label="项目金额"
                          required>
              <el-input-number v-model="form.projectAmount"
                               :precision="2"
                               :step="1000"
                               :min="0"
                               :disabled="isViewMode"
                               class="full-width-input"
                               @change="onProjectAmountChange" />
            </el-form-item>
          </el-col>

          <el-col :xs="24"
                  :sm="12"
                  :md="8"
                  :lg="6">
            <el-form-item label="数量"><!-- 仓库数量 -->
              <el-input-number v-model="form.warehouseQuantity"
                               :precision="0"
                               :step="1"
                               :min="1"
                               :disabled="isViewMode"
                               class="full-width-input"
                               @change="onWarehouseQuantityChange" />
            </el-form-item>
          </el-col>

          <el-col :xs="24"
                  :sm="12"
                  :md="8"
                  :lg="6">
            <el-form-item label="WMS金额">
              <el-input-number v-model="form.wmsAmount"
                               :precision="2"
                               :step="1000"
                               :min="0"
                               class="full-width-input" />
            </el-form-item>
          </el-col>

          <el-col :xs="24"
                  :sm="12"
                  :md="8"
                  :lg="6">
            <el-form-item label="WCS金额">
              <el-input-number v-model="form.wcsAmount"
                               :precision="2"
                               :step="1000"
                               :min="0"
                               class="full-width-input" />
            </el-form-item>
          </el-col>

          <el-col :xs="24"
                  :sm="12"
                  :md="8"
                  :lg="6">
            <el-form-item label="接口金额">
              <el-input-number v-model="form.interfaceAmount"
                               :precision="2"
                               :step="1000"
                               :min="0"
                               class="full-width-input" />
            </el-form-item>
          </el-col>

          <el-col :xs="24"
                  :sm="12"
                  :md="8"
                  :lg="6">
            <el-form-item label="实施费（基数）">
              <el-input-number v-model="form.baseImplementationFee"
                               :precision="2"
                               :step="1000"
                               :min="0"
                               class="full-width-input" />
            </el-form-item>
          </el-col>

          <el-col :xs="24"
                  :sm="12"
                  :md="8"
                  :lg="6">
            <el-form-item label="物料最终价格">
              <el-input-number v-model="form.materialPrice"
                               :precision="2"
                               :min="0"
                               :disabled="true"
                               class="full-width-input" />
              <!--<div v-if="form.materialCoefficient !== 1" class="coefficient-info">-->
              <!--  基础价格 × {{ form.materialCoefficient }} 系数-->
              <!--</div>-->
            </el-form-item>
          </el-col>

          <el-col :xs="24"
                  :sm="24"
                  :md="8"
                  :lg="6">
            <el-form-item label="物料系数加成">
              <el-select v-model="form.materialCoefficient" filterable
                         placeholder="请选择系数加成"
                         @change="handleMaterialCoefficientChange"
                         class="full-width-input">
                <el-option v-for="item in materialsOptions"
                           :key="item.value"
                           :label="`${item.label} (${item.value})`"
                           :value="item.value" />
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 物料明细卡片 -->
      <el-card class="form-card"
               shadow="hover">
        <template #header>
          <div class="card-header">
            <span>物料明细</span>
            <el-button type="primary"
                       size="small"
                       :disabled="isViewMode"
                       @click="openBaseMaterialSelect">
              <el-icon>
                <Plus />
              </el-icon>
              添加物料
            </el-button>
          </div>
        </template>

        <el-table :data="form.materialItems"
                  border
                  stripe
                  class="material-table">
          <el-table-column label="序号"
                           type="index"
                           width="60"
                           align="center" />

          <el-table-column label="物料名称"
                           prop="materialName"
                           min-width="170"
                           show-overflow-tooltip />

          <el-table-column label="品牌"
                           prop="brand"
                           min-width="120"
                           show-overflow-tooltip />

          <el-table-column label="单价"
                           prop="purchasePrice"
                           min-width="100">
            <template #default="scope">
              <span class="price-value">{{
                  scope.row.purchasePrice ? `¥${scope.row.purchasePrice.toFixed(2)}` : '--'
                }}</span>
            </template>
          </el-table-column>

          <el-table-column label="数量"
                           prop="quantity"
                           min-width="100">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity"
                               :min="1"
                               :precision="0"
                               @change="() => handleMaterialQuantityChange(scope.row)"
                               class="table-input-number" />
            </template>
          </el-table-column>

          <el-table-column label="总价"
                           prop="totalPrice"
                           min-width="120">
            <template #default="scope">
              <span class="price-value">{{ scope.row.totalPrice ? `¥${scope.row.totalPrice.toFixed(2)}` : '--' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作"
                           width="80"
                           align="center">
            <template #default="scope">
              <el-button type="danger"
                         circle
                         size="small"
                         :disabled="isViewMode"
                         @click="removeMaterialItem(scope.$index)">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="material-summary"
             v-if="form.materialItems.length > 0">
          <div class="summary-item">
            <span class="summary-label">物料小计:</span>
            <span class="summary-value">¥{{ form.materialBasePrice.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <div class="summary-label">系数加成:</div>
            <div class="coefficient-selector">
              <span v-if="form.materialCoefficient !== 1"
                    class="coefficient-value">
                × {{ form.materialCoefficient }}
              </span>
            </div>
          </div>
          <div class="summary-item total">
            <span class="summary-label">物料总价:</span>
            <span class="summary-value">¥{{ form.materialPrice.toFixed(2) }}</span>
          </div>
        </div>

        <div v-if="form.materialItems.length === 0"
             class="empty-material">
          <el-empty description="暂无物料数据，请点击添加物料按钮进行添加" />
        </div>
      </el-card>

      <!-- 实施项明细卡片 -->
      <el-card class="form-card"
               shadow="hover">
        <template #header>
          <div class="card-header">
              <span>实施项明细</span>

            <div>
              <el-tooltip
                  class="box-item"
                  effect="light"
                  placement="top"
                  raw-content
              >
                <template #content>
                  <div v-html="implementationItemNotice"></div>
                </template>

                <el-icon style="color: red; cursor: pointer;">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>

              <el-button type="primary"
                         size="small"
                         :disabled="isViewMode"
                         @click="addImplementationItem">
                <el-icon>
                  <Plus />
                </el-icon>
                添加实施项
              </el-button>
            </div>

          </div>
        </template>

        <el-table :data="form.implementationItem"
                  border
                  stripe
                  class="implementation-table">
          <el-table-column label="序号"
                           type="index"
                           width="60"
                           align="center" />

          <el-table-column label="实施项名称"
                           prop="name"
                           min-width="170">
            <template #default="scope">
                                  <el-select v-model="scope.row.name" filterable
                         placeholder="请选择实施项"
                         class="full-width-input"
                         @change="() => handleImplementationNameChange(scope.row)">
                <el-option v-for="item in implementationNameOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value" />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="数量"
                           prop="quantity"
                           min-width="50">
            <template #default="scope">
              <el-input v-model="scope.row.quantity"
                               :min="1"
                               :precision="0"
                               @change="() => handleQuantityChange(scope.row)"
                               class="table-input-number" />
            </template>
          </el-table-column>

          <el-table-column label="单价"
                           prop="unit_price"
                           min-width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.unitPrice"
                               :precision="2"
                               :min="0"
                               @change="() => handleQuantityChange(scope.row)"
                               class="table-input-number" />
            </template>
          </el-table-column>

          <el-table-column label="总价"
                           prop="totalPrice"
                           min-width="70">
            <template #default="scope">
              <span class="price-value">{{ scope.row.totalPrice.toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作"
                           width="80"
                           align="center">
            <template #default="scope">
              <el-button type="danger"
                         circle
                         size="small"
                         :disabled="isViewMode"
                         @click="removeImplementationItem(scope.$index)">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="implementation-summary">
          <div class="summary-item">

            <span class="summary-label">实施项小计:</span>
            <span class="summary-value">{{ implementationItemsTotal.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <div class="summary-label">系数加成:</div>
            <div class="coefficient-selector">
              <el-select v-model="form.implementationCoefficient" filterable
                         placeholder="请选择系数加成"
                         @change="handleCoefficientChange"
                         style="width: 150px">
                <el-option v-for="item in coefficientOptions"
                           :key="item.value"
                           :label="`${item.label} (${item.value})`"
                           :value="item.value" />
              </el-select>
              <span v-if="form.implementationCoefficient !== 1"
                    class="coefficient-value">
                × {{ form.implementationCoefficient }}
              </span>
            </div>
          </div>
          <div class="summary-item total">
            <span class="summary-label">实施总价:</span>
            <span class="summary-value">{{ form.totalImplementationPrice.toFixed(2) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 额外费用与备注卡片 -->
      <el-card class="form-card"
               shadow="hover">
        <template #header>
          <div class="card-header">
            <span>额外费用与备注</span>
            <el-tooltip
                class="box-item"
                effect="light"
                placement="top"
                raw-content
            >
              <template #content>
                <div v-html="softwarePlanNotice"></div>
                <!--<div style="font-family:Arial, sans-serif; font-size:14px; line-height:1.8;">
                  <p style="color:red;">注意事项(规划技术部容易发生、反复出现的问题)：</p>
                  <p style="color:red;">1. 如果方案出现不对，或者清单错项、漏项，不予核价，退回要求重新整理</p>
                  <p style="color:red;">2. 堆垛机数量超过6台以后，服务器按照20000元/台成本核价，且双机热备</p>
                  <p style="color:red;">3. 堆垛机数量超过10台以后，服务器按照30000元/台成本核价，且双机热备</p>
                  <p style="color:red;">4. 注意各配置数量/参数等，互相之间是否能匹配上</p>
                  <p style="color:red;">5.
                    如果项目中含有AGV且RCS为厂家提供，或者是有厂家供货的软件，需要另行配置服务器</p>
                  <p style="color:red;">6. 检查穿梭库、AGV等供货时，是否有列无线网络等设备清单</p>
                  <p style="color:red;">7. 四向车服务器2.8万一台，AGV的RCS服务器2.2万一台</p>
                  <p style="color:red;">8. 军工项目按照常规项目的3倍实施费处理</p>
                  <p style="color:red;">9. 一个项目中存在多个库区，独立配置WCS，按分批进场处理</p>
                  <p style="color:red;">10. 四向车、AGV项目，分别配置服务器，不与WMS/WCS共用服务器</p>
                  <p style="color:red;">11.
                    若有明确关于系统部分的招标要求，将文件交于系统集成部门，让他们评估是否有增减和调整</p>
                  <p style="color:red;">12. 堆垛机不超过3台，软件及实施价不超过15万</p>

                  <p style="color:#1F4E78;">13.
                    陪产时间15天以上的天数，一个库按1000元/天，24小时陪产按2000元/天，跨厂房建筑需单独计算</p>
                  <p style="color:#1F4E78;">14.
                    AGV、CTU项目的实施费是硬件（车体、二维码、服务器、电视机等）总价的15%(中扬实施)</p>

                  <p style="color:#572808;">15.
                    AGV、CTU项目的无线网路硬件及实施费用，待复核按6800元每套是否满足(中扬实施)</p>

                  <p style="color:#1F4E78;">16. 一个项目，设备布置在不同的厂房建筑内，没有连通；WMS按一套，WCS单独计算</p>
                  <p style="color:#1F4E78;">17.
                    若项目拆分成一期二期；二期WMS先按新项目报价，后续有争议可按1至4万酌情报价</p>
                  <p style="color:#1F4E78;">18. 不同类型的两个库，接口费用要算两套（如一套对接牛眼，一套对接海康）</p>
                  <p style="color:#1F4E78;">19. 国外项目24小时的，距离默认+2w，实施费*3，距离因素不*3</p>
                  <p style="color:#1F4E78;">20.
                    改造项目的软件核价需要售前跟软件对接方案改造具体内容，按软件人员报价</p>
                  <p style="color:#1F4E78;">21. 一轨双堆垛机 WCS+1万</p>
                </div>-->
              </template>

              <el-icon style="color: red; cursor: pointer;">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :xs="24"
                  :sm="12">
            <el-form-item label="额外费用">
              <el-input-number v-model="form.extraCost"
                               :precision="2"
                               :step="1000"
                               :min="0"
                               class="full-width-input" />
            </el-form-item>
          </el-col>

          <el-col :xs="24"
                  :sm="12">
            <el-form-item label="额外费用说明">
              <el-input v-model="form.extraCostDescription"
                        placeholder="请输入额外费用说明" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input v-model="form.remark"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注信息" />
        </el-form-item>
      </el-card>

      <!-- 总计金额卡片 -->
      <el-card class="total-card"
               shadow="hover">
        <div class="total-display">
          <div class="total-label">软件核价总计</div>
          <div class="total-value">¥ {{ form.totalPrice.toFixed(2) }}</div>
        </div>
      </el-card>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <el-button v-if="!isViewMode"
                   type="primary"
                   @click="submitForm"
                   size="large">
          <el-icon>
            <Check />
          </el-icon>
          提交核价单
        </el-button>
        <el-button size="large"
                   @click="resetForm">
          <el-icon>
            <Close />
          </el-icon>
          {{ isViewMode ? '返回' : '取消' }}
        </el-button>
      </div>
    </el-form>
  </div>

  <!-- 仓库选择器组件 -->
  <ArchiveSelector v-model="warehouseSelectorVisible"
                   title="选择仓库"
                   :search-fields="warehouseSearchFields"
                   :table-columns="warehouseTableColumns"
                   :fetch-data-api="getWarehouseList"
                   :multiple="false"
                   @confirm="handleWarehouseSelect" />

  <!-- 项目选择器组件 -->
  <ArchiveSelector v-model="projectSelectorVisible"
                   title="选择项目"
                   :search-fields="projectSearchFields"
                   :table-columns="projectTableColumns"
                   :fetch-data-api="getProjectList"
                   :multiple="false"
                   @confirm="handleProjectSelect" />

  <!-- 添加基础物料选择弹框 -->
  <material-dialog ref="baseMaterialDialogRef"
                   :multiple="true"
                   @handleMaterialSelectionChange="handleMaterialSelectionChange"
                   @confirmMaterialSelect="confirmMaterialSelect" />

</template>

<style scoped lang="scss">
.pricing-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;

  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
    padding-bottom: 12px;
    position: relative;
    display: inline-block;

    &:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 3px;
      background: linear-gradient(90deg, #409eff, rgba(64, 158, 255, 0.3));
      border-radius: 3px;
    }
  }
}

.pricing-form {
  .form-card {
    margin-bottom: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      position: relative;
      padding-left: 12px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background-color: #409eff;
        border-radius: 2px;
      }
    }
  }

  .selector-input {
    .el-input__wrapper {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }
  }

  .material-price {
    margin-top: 8px;
    font-size: 13px;
    color: #606266;

    span {
      color: #f56c6c;
      font-weight: 600;
    }
  }

  .full-width-input {
    width: 100%;
  }

  .table-input-number {
    width: 100%;
  }

  .implementation-table {
    margin-bottom: 20px;
    border-radius: 4px;
    overflow: hidden;
  }

  .implementation-summary {
    padding: 16px;
    background-color: #f8f9fc;
    border-radius: 6px;
    border: 1px dashed #dcdfe6;

    .summary-item {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-bottom: 8px;

      &.total {
        margin-top: 12px;
        padding-top: 12px;
        border-top: 1px dashed #dcdfe6;

        .summary-label,
        .summary-value {
          font-size: 16px;
          font-weight: 600;
        }

        .summary-value {
          color: #409eff;
        }
      }

      .summary-label {
        margin-right: 16px;
        color: #606266;
      }

      .summary-value {
        min-width: 100px;
        text-align: right;
        color: #f56c6c;
        font-weight: 500;
      }
    }
  }

  .price-value {
    color: #f56c6c;
    font-weight: 600;
  }

  .total-card {
    background: linear-gradient(135deg, #409eff, #007aff);
    color: white;
    margin-bottom: 24px;
    border: none;

    .total-display {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;

      .total-label {
        font-size: 18px;
        font-weight: 500;
      }

      .total-value {
        font-size: 28px;
        font-weight: 700;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    margin-top: 32px;
    margin-bottom: 40px;

    .el-button {
      min-width: 140px;
      margin: 0 12px;
      padding: 12px 24px;
      border-radius: 4px;
      font-weight: 500;
    }
  }
}

.coefficient-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.coefficient-value {
  font-weight: 600;
  color: #409eff;
}

.coefficient-info {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}

.material-table {
  margin-bottom: 15px;
}

.material-summary {
  padding: 16px;
  background-color: #f8f9fc;
  border-radius: 6px;
  border: 1px dashed #dcdfe6;
  margin-top: 15px;

  .summary-item {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 8px;

    &.total {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px dashed #dcdfe6;

      .summary-label,
      .summary-value {
        font-size: 16px;
        font-weight: 600;
      }

      .summary-value {
        color: #409eff;
      }
    }

    .summary-label {
      margin-right: 16px;
      color: #606266;
    }

    .summary-value {
      min-width: 100px;
      text-align: right;
      color: #f56c6c;
      font-weight: 500;
    }
  }
}

.empty-material {
  padding: 30px 0;
}
</style>
